#! /usr/bin/env python
# -*- encoding: UTF-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf8')
from naoqi import ALProxy
import time
from HttpRequest import requestApi

ROBOT_IP = "192.168.1.110"

SELF_INTRODUCTION = "我是来自武汉大学,训创中心的,pepper，很高兴认识你呢"

# 下面是能识别的句子，只是分类而且，最后都合在一起了
word_time = ["现在几点了","今天周几","今天几号","日期"]
word_personal = ["你是什么星座","你喜欢什么","做个自我介绍吧","你喜欢什么颜色","你喜欢什么","自我介绍"]
word_wuhan = ["武汉天气预报","今天武汉天气怎么样","武汉","武汉怎么样"]
wordList = ["你好","hello","goodbye","再见","说个笑话","唱首歌吧","唱歌","介绍武汉大学吧"]
# 设定要识别的单词或短语表

wordList = wordList + word_time + word_personal + word_wuhan

def speak(word):
    tts = ALProxy("ALTextToSpeech",ROBOT_IP,9559)
    # 语速
    tts.setParameter("speed", 200)
    tts.say(str(word))

def startDetectionWord():  
    NoWordTime = 0
    # 在模块上创建一个代理
    asr = ALProxy("ALSpeechRecognition",ROBOT_IP,9559) 

    robotMemory = ALProxy("ALMemory", ROBOT_IP, 9559)
    # 设定ASR模块的语言 
    asr.setLanguage("Chinese")  

    # 先暂停
    asr.pause(True)
    asr.setVocabulary(wordList,False)
    # 设置进程名,停止检测时也是通过该进程名进行停止
    rec(asr, robotMemory, 0, NoWordTime)
    
    
def rec(asr, robotMemory, index, NoWordTime):
    # 内存先清掉
    if index != 0:
        robotMemory.removeData("WordRecognized")
        robotMemory.insertData("WordRecognized", ["",0])
    asr.subscribe("TEST_ASR")  
    asr.pause(False)
    print("语音识别引擎已启动")
    time.sleep(4)  
    sentence = robotMemory.getData("WordRecognized")
    print(sentence)
    if sentence[1] > 0.4:  
        if sentence[0] == "goodbye" or sentence[0] == "再见":
            # 相当于关闭进程 
            asr.unsubscribe("TEST_ASR")
            speak(sentence[0])
            return
        elif sentence[0] == "做个自我介绍吧" or sentence[0] == "自我介绍":
            speak(SELF_INTRODUCTION)
        else:          
            print("sentence[0]: " + sentence[0])               
            response = requestApi(sentence[0])
            print(response)
            speak(response)
            index += 1
            NoWordTime = 0
            rec(asr, robotMemory, index, NoWordTime)       
    else:
        if NoWordTime == 2:
            print("长时间没收到信息退出")
            # 相当于关闭进程 
            asr.unsubscribe("TEST_ASR")
            return
        speak("我没听清,再说得准确一点吧")
        index += 1
        NoWordTime += 1
        rec(asr, robotMemory, index, NoWordTime) 
   
if __name__ == "__main__":
    startDetectionWord()   